/*
 * INodeIndirect.cpp
 *
 *  Created on: Jul 7, 2009
 *      Author: elkobir
 */

#include "INodeIndirect.h"

INodeIndirect::INodeIndirect(int blockSizeInBytes) {
	_blockSizeInBytes = blockSizeInBytes;
	_addressesInBlockCount = (_blockSizeInBytes / 4);

	unsigned char* data = Utils::InitBytes(_blockSizeInBytes);

	fromBytes(data);

}

INodeIndirect::INodeIndirect(int blockSizeInBytes, unsigned char* data) {
	_blockSizeInBytes = blockSizeInBytes;
	_addressesInBlockCount = (_blockSizeInBytes / 4);

	fromBytes(data);

}

INodeIndirect::~INodeIndirect() {
	// TODO Auto-generated destructor stub
}

unsigned char* INodeIndirect::toBytes(){
	unsigned char* res = Utils::InitBytes(_blockSizeInBytes);
	//who ever control res control his release memory

	for(unsigned int i = 0; i < (unsigned)_addressesInBlockCount; i++){
		int val = this->_addresses.at(i);
		Utils::IntToByte(val, res, i*4 );
	}

	return res;
}

void INodeIndirect::fromBytes(unsigned char* data){

	_addresses.clear();

	for(int i = 0; i<_addressesInBlockCount; i++){
		_addresses.push_back(0);
	}

	for(unsigned int i = 0; i < (unsigned)_addressesInBlockCount; i++){
		int val = Utils::GetInt(data, i*4);
		this->_addresses[i] = val;
	}

}




vector<int>* INodeIndirect::getBlockList(){
	vector<int>* result = new vector<int>();

	for (int i = 0; i < _addresses.size(); i++){
		int val = _addresses.at(i);
		if(val != 0){
			result->push_back(val);
		}
	}

	return result;
}

int INodeIndirect::getBlockAt(int i){
	int localI = i - 10;
	if(localI<0 | localI>= _addressesInBlockCount){
		ostringstream str;
		str << "INodeIndirect::getBlockAt - index out of bounds " << localI << endl;
		Log::log(str, 0, "error");
		return -1;
	}

	int ans = _addresses.at(localI);
	return ans;
}

void INodeIndirect::setBlockAt(int i, int dBlockNum){
	int localI = i - 10;
	if(localI<0 | localI>= _addressesInBlockCount){
		ostringstream str;
		str << "INodeIndirect::setBlockAt - index out of bounds " << localI << endl;
		Log::log(str, 0, "error");
	}
	_addresses[localI] = dBlockNum;
}




